<?php
namespace Core\Controller;

use Core\Constant;
use Core\Exception\BusinessException;
use Core\Service\Authenticate\IdentityManagerInterface;
use Core\Session\AdminSessionHelper;
use Core\Session\ApplicationSessionHelper;
use Core\Session\FrontSessionHelper;
use Core\Session\RestaurantSessionHelper;
use Model\TableFinder;
use Model\User;
use Resmodel\Factory\ResTableFinder;
use Resmodel\Factory\ResTableGatewayFactory;
use Zend\Db\Adapter\Adapter;
use Zend\Mvc\MvcEvent;
use Zend\View\Model\ViewModel;
use Zend\View\Model\JsonModel;

class RestaurantAdminBaseController extends  BaseController{

    /**
     * @var User
     */
    protected $_user;

    /**
     * @var IdentityManagerInterface;
     */
    protected $identityManager;

    /**
     * @var \Zend\View\Model\ViewModel
     */
    protected $viewModel;


    /**
     * @var ResTableFinder
     */
    protected $resTableFinder;

    /**
     * @var string
     */
    protected $domainCode;

    /**
     * @return ResTableFinder
     */

    private $domainAdapter;

    private function getDomainAdapter(){
        if(!$this->domainAdapter){
            $dbname = str_replace('-', '_',$this->domainCode);
            $sm = $this->getServiceLocator();
            $config = $sm->get('Config');
            $dbConf = $config['db'];
            $dsn = $dbConf['dsn'];
            $tmpArr = explode(';',$dsn);
            $tmpArr2 = explode('=',$tmpArr[0]);
            $dsn=$tmpArr2[0].'='.$dbname.';'.$tmpArr[1];
            $dbConf['dsn'] = $dsn;
            $this->domainAdapter = new Adapter($dbConf);
        }

        return $this->domainAdapter;
    }

    /**
     * @return ResTableFinder
     */
    public function getResTableFinder()
    {
        if(!$this->resTableFinder){
            $this->resTableFinder = $this->getServiceLocator()->
                get('ResTableFinder');
            $this->resTableFinder->setDomain($this->domainCode);
            $this->resTableFinder->setDbAdapter($this->getDomainAdapter());
        }

        return $this->resTableFinder;
    }

    public function __construct(IdentityManagerInterface $identityManager)
    {
        $this->identityManager = $identityManager;
        $this->viewModel = new ViewModel();
    }

    /**
     * @return \Zend\View\Model\ViewModel
     */
    public function getViewModel()
    {
        return $this->viewModel;
    }


    public function onDispatch(MvcEvent $e)
    {

        $this->checkAAA();

        $this->setUser(FrontSessionHelper::getUser());
        $controller = $this->getEvent()->getRouteMatch()->getParam('controller');
        $action = $this->getEvent()->getRouteMatch()->getParam('action');
        ApplicationSessionHelper::setCurrentModule('ad_restaurant');
        ApplicationSessionHelper::setCurrentController($controller);
        ApplicationSessionHelper::setCurrentAction($action);

        $restaurantTable = $this->getTableFinder()->getRestaurantTable();
        $domainCode = strtolower($this->params()->fromRoute('domain'));
        RestaurantSessionHelper::setDomainCode($domainCode);
        $restaurant = $restaurantTable->getByDomainCode($domainCode);
        $this->layout()->setVariable('domainItem',$restaurant);
        $this->getViewModel()->setVariable('domainItem',$restaurant);
        $this->domainCode = $domainCode;
        ResTableGatewayFactory::setDomain($this->domainCode);
        ResTableGatewayFactory::setLang(FrontSessionHelper::getCurrentLang());
        ResTableGatewayFactory::setDbAdapter($this->getDomainAdapter());
        return parent::onDispatch($e);
    }

    public function initPageWithLayout(){
        $pageId = $this->params()->fromRoute('pageId');
        $pageTable = $this->getTableFinder()->getPageTable();
        $page = $pageTable->getPage($pageId);
        $template = $page->getTemplate();
        $this->layout($template->file_name.'.php');
        $this->layout()->setVariable('templateItem',$template);
        $this->getViewModel()->setVariable('pageItem',$page);
    }

    /**
     * @param \Core\Service\Authenticate\IdentityManagerInterface $identityManager
     */
    public function setIdentityManager($identityManager)
    {
        $this->identityManager = $identityManager;
    }

    /**
     * @return \Core\Service\Authenticate\IdentityManagerInterface
     */
    public function getIdentityManager()
    {
        return $this->identityManager;
    }


    /**
     * @param \Model\User $user
     */
    public function setUser($user)
    {
        $this->_user = $user;
    }

    /**
     * @return \Model\User
     */
    public function getUser()
    {
        return $this->_user;
    }

    protected function genJsonErrorView(\Exception $ex){
        if($ex instanceof BusinessException){
            $msg = $ex->getMessage();
        }else{
            $msg = 'Lỗi hệ thống. Vui lòng liên hệ chúng tôi để khắc phục.';
        }
        return new  JsonModel(array('success'=>false, 'msg'=>$msg));
    }


    protected function genErrorView(\Exception $ex){
        if($ex instanceof BusinessException){
            $msg = $ex->getMessage();
        }else{
            $msg = 'Lỗi hệ thống. Vui lòng liên hệ chúng tôi để khắc phục.';
        }
        $viewModel = new  ViewModel(array('error_msg' => $msg));
        $viewModel->setTerminal(true);
        return $viewModel;
    }

    private function checkAAA()
    {
        //check authenticate
        $user = FrontSessionHelper::getUser();
            if(!$user) throw new BusinessException('Vui lòng đăng nhập để thực hiện chức năng này.');
        //check belonged to domain
        $domainCode = $this->params()->fromRoute('domain');
        if(!$user->isHavingDomain($domainCode))
            throw new BusinessException('Bạn chưa được cấp quyền truy cập chức năng này');
        //check having staff role
        $roleTable = $this->getTableFinder()->getRoleTable();
        $roleStaff = $roleTable->getRoleByCode(Constant::$SYSTEM_ROLE_CODE_RES_STAFF);
        if(!$user->isHavingRole($roleStaff->id))
            throw new BusinessException('Bạn chưa được cấp quyền quản trị chức năng nhà hàng');
        //@todo: check  RBAC of domain


        //audit
        if($user->is_log == 1){
            //@todo: log user action
        }


    }


}
